package com.imm.da.base.vm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.imm.da.base.BaseFragment
import java.lang.reflect.ParameterizedType

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by Administrator
 * @date on 2021 2021/11/14 11:57
 */
abstract class BaseVMFragment<VM : ViewModel, VD : ViewDataBinding>(@LayoutRes val resId: Int) : BaseFragment(resId) {

    /**
     * 可调用的 ViewModel
     */
    protected val viewModel: VM by lazy {
        val vmClass = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        ViewModelProvider(this)[vmClass]
    }

    private var _binding: VD? = null

    protected val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = dataBinding(inflater, layoutId, container)
        _binding?.lifecycleOwner = this
        return _binding?.root
    }

    private fun <V : VD> dataBinding(
        inflater: LayoutInflater,
        @LayoutRes layoutId: Int,
        container: ViewGroup?
    ) : V = DataBindingUtil.inflate(inflater, layoutId, container, false)

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initFragment()
    }

    /**
     * 初始化数据
     */
    abstract fun initFragment()

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}